<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Boss直聘数据展示系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <style>
        .stats-card {
            transition: transform 0.3s;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .job-card {
            border-left: 4px solid #007bff;
            transition: all 0.3s;
        }
        .job-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .salary-high {
            color: #dc3545;
            font-weight: bold;
        }
        .chart-container {
            height: 300px;
            margin-bottom: 20px;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="bi bi-graph-up"></i> Boss直聘数据展示系统
            </a>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- 统计卡片 -->
        <div class="row" id="stats-cards">
            <div class="col-md-3 mb-4">
                <div class="card stats-card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 id="total-jobs">0</h4>
                                <p class="mb-0">总职位数</p>
                            </div>
                            <div class="align-self-center">
                                <i class="bi bi-briefcase fs-1"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-4">
                <div class="card stats-card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 id="total-cities">0</h4>
                                <p class="mb-0">覆盖城市</p>
                            </div>
                            <div class="align-self-center">
                                <i class="bi bi-geo-alt fs-1"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-4">
                <div class="card stats-card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 id="total-companies">0</h4>
                                <p class="mb-0">公司数量</p>
                            </div>
                            <div class="align-self-center">
                                <i class="bi bi-building fs-1"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-4">
                <div class="card stats-card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 id="latest-time">-</h4>
                                <p class="mb-0">最新数据</p>
                            </div>
                            <div class="align-self-center">
                                <i class="bi bi-clock fs-1"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">城市分布</h5>
                    </div>
                    <div class="card-body">
                        <div id="city-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">关键词分布</h5>
                    </div>
                    <div class="card-body">
                        <div id="keyword-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">薪资分布</h5>
                    </div>
                    <div class="card-body">
                        <div id="salary-chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">职位搜索</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="search-keyword" placeholder="搜索职位或关键词...">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" id="search-city">
                            <option value="">所有城市</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" id="search-salary">
                            <option value="">所有薪资</option>
                            <option value="0-10">10K以下</option>
                            <option value="10-20">10-20K</option>
                            <option value="20-30">20-30K</option>
                            <option value="30+">30K以上</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-primary w-100" onclick="loadJobs()">搜索</button>
                    </div>
                    <div class="col-md-3 text-end">
                        <button class="btn btn-outline-secondary" onclick="exportData()">
                            <i class="bi bi-download"></i> 导出数据
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 职位列表 -->
        <div class="card mt-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">职位列表</h5>
                <span class="text-muted" id="job-count">共 0 个职位</span>
            </div>
            <div class="card-body">
                <div class="loading" id="jobs-loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载数据...</p>
                </div>
                <div id="jobs-container"></div>

                <!-- 分页 -->
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center" id="pagination"></ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- 职位详情模态框 -->
    <div class="modal fade" id="jobDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="jobDetailTitle">职位详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="jobDetailContent">
                    <!-- 详情内容将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        const perPage = 20;

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            loadStats();
            loadCities();
            loadJobs();
        });

        // 加载统计信息
        async function loadStats() {
            try {
                const response = await fetch('/api/stats');
                const data = await response.json();

                if (data.success) {
                    // 更新统计卡片
                    document.getElementById('total-jobs').textContent = data.data.total_jobs.toLocaleString();
                    document.getElementById('total-cities').textContent = data.data.total_cities;
                    document.getElementById('total-companies').textContent = data.data.total_companies.toLocaleString();
                    document.getElementById('latest-time').textContent = data.data.latest_time || '-';

                    // 绘制图表
                    renderCityChart(data.data.city_distribution);
                    renderKeywordChart(data.data.keyword_distribution);
                    renderSalaryChart(data.data.salary_distribution);
                }
            } catch (error) {
                console.error('加载统计信息失败:', error);
            }
        }

        // 加载城市列表
        async function loadCities() {
            try {
                const response = await fetch('/api/cities');
                const data = await response.json();

                if (data.success) {
                    const citySelect = document.getElementById('search-city');
                    data.data.forEach(city => {
                        const option = document.createElement('option');
                        option.value = city;
                        option.textContent = city;
                        citySelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载城市列表失败:', error);
            }
        }

        // 加载职位列表
        async function loadJobs(page = 1) {
            currentPage = page;
            const keyword = document.getElementById('search-keyword').value;
            const city = document.getElementById('search-city').value;
            const salary = document.getElementById('search-salary').value;

            // 显示加载动画
            document.getElementById('jobs-loading').style.display = 'block';
            document.getElementById('jobs-container').innerHTML = '';

            try {
                const params = new URLSearchParams({
                    page: page,
                    per_page: perPage,
                    keyword: keyword,
                    city: city,
                    salary_range: salary
                });

                const response = await fetch(`/api/jobs?${params}`);
                const data = await response.json();

                if (data.success) {
                    renderJobs(data.data);
                    renderPagination(data.pagination);
                    document.getElementById('job-count').textContent = `共 ${data.pagination.total} 个职位`;
                }
            } catch (error) {
                console.error('加载职位列表失败:', error);
            } finally {
                document.getElementById('jobs-loading').style.display = 'none';
            }
        }

        // 渲染职位列表
        function renderJobs(jobs) {
            const container = document.getElementById('jobs-container');

            if (jobs.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-5">
                        <i class="bi bi-inbox fs-1 text-muted"></i>
                        <p class="text-muted mt-2">暂无数据</p>
                    </div>
                `;
                return;
            }

            let html = '';
            jobs.forEach(job => {
                html += `
                    <div class="card job-card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-8">
                                    <h5 class="card-title">${escapeHtml(job.job_title)}</h5>
                                    <p class="card-text">
                                        <span class="salary-high">${escapeHtml(job.job_salary)}</span>
                                        | ${escapeHtml(job.job_company)}
                                        | ${escapeHtml(job.company_city)}${job.job_lable ? ' | ' + escapeHtml(job.job_lable) : ''}
                                    </p>
                                    ${job.job_skill ? `<p class="card-text"><small class="text-muted">技能要求: ${escapeHtml(job.job_skill)}</small></p>` : ''}
                                </div>
                                <div class="col-md-4 text-end">
                                    <p class="card-text"><small class="text-muted">${job.keyword}</small></p>
                                    <p class="card-text"><small class="text-muted">${job.crawl_time}</small></p>
                                    <button class="btn btn-outline-primary btn-sm" onclick="showJobDetail(${job.id})">查看详情</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            container.innerHTML = html;
        }

        // 渲染分页
        function renderPagination(pagination) {
            const container = document.getElementById('pagination');
            const totalPages = pagination.pages;

            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }

            let html = '';
            const maxVisible = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
            let endPage = Math.min(totalPages, startPage + maxVisible - 1);

            if (endPage - startPage + 1 < maxVisible) {
                startPage = Math.max(1, endPage - maxVisible + 1);
            }

            // 上一页
            html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="loadJobs(${currentPage - 1})">上一页</a>
            </li>`;

            // 页码
            for (let i = startPage; i <= endPage; i++) {
                html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="javascript:void(0)" onclick="loadJobs(${i})">${i}</a>
                </li>`;
            }

            // 下一页
            html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="javascript:void(0)" onclick="loadJobs(${currentPage + 1})">下一页</a>
            </li>`;

            container.innerHTML = html;
        }

        // 显示职位详情
        async function showJobDetail(jobId) {
            // 这里可以添加获取详细信息的API调用
            // 暂时简单显示
            const modal = new bootstrap.Modal(document.getElementById('jobDetailModal'));
            document.getElementById('jobDetailTitle').textContent = '职位详情';
            document.getElementById('jobDetailContent').innerHTML = '<p>详情功能开发中...</p>';
            modal.show();
        }

        // 导出数据
        function exportData() {
            const keyword = document.getElementById('search-keyword').value;
            const city = document.getElementById('search-city').value;
            const salary = document.getElementById('search-salary').value;

            const params = new URLSearchParams({
                keyword: keyword,
                city: city,
                salary_range: salary
            });

            window.open(`/api/export?${params}`, '_blank');
        }

        // 图表渲染函数
        function renderCityChart(data) {
            const chart = echarts.init(document.getElementById('city-chart'));
            const option = {
                tooltip: { trigger: 'axis' },
                xAxis: { type: 'category', data: data.map(item => item.company_city) },
                yAxis: { type: 'value' },
                series: [{
                    data: data.map(item => item.count),
                    type: 'bar',
                    itemStyle: { color: '#5470c6' }
                }]
            };
            chart.setOption(option);
        }

        function renderKeywordChart(data) {
            const chart = echarts.init(document.getElementById('keyword-chart'));
            const option = {
                tooltip: { trigger: 'item' },
                series: [{
                    type: 'pie',
                    radius: '70%',
                    data: data.map(item => ({ value: item.count, name: item.keyword })),
                    emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
                }]
            };
            chart.setOption(option);
        }

        function renderSalaryChart(data) {
            const chart = echarts.init(document.getElementById('salary-chart'));
            const option = {
                tooltip: { trigger: 'item' },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    data: data.map(item => ({ value: item.count, name: item.salary_range })),
                    emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
                }]
            };
            chart.setOption(option);
        }

        // HTML转义函数
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 搜索框回车事件
        document.getElementById('search-keyword').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                loadJobs(1);
            }
        });
    </script>
</body>
</html>